package com.tao.service.product;

import com.github.pagehelper.PageHelper;
import com.tao.dao.ProductMapper;
import com.tao.pojo.ProductExample;
import com.tao.pojo.ProductQuery;
import com.tao.pojo.ProductWithBLOBs;
import com.tao.pojo.Sku;
import com.tao.service.sku.IskuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ProductServiceImpl implements IproductService {

	@Autowired
	ProductMapper productMapper;
	
	@Autowired
	IskuService skuService;
	@Override
	@Transactional
	/**
	 * 添加了事务处理在插入商品的同时需要插入SKU
	 */
	public int add(ProductWithBLOBs productWithBLOBs) {
		int result=0;
		result+=productMapper.insertSelective(productWithBLOBs);
		String[] storages= productWithBLOBs.getStorageList().split(",");
		String[] colors= productWithBLOBs.getColorList().split(",");
		for (String color : colors) {
			for (String storage : storages) {
				Sku sku=new Sku();
				sku.setColorId(Integer.parseInt(color));
				sku.setStorageId(Integer.parseInt(storage));
				sku.setPrice(productWithBLOBs.getPrice());
				sku.setSales(0);
				sku.setSort(1);
				sku.setStock(100);
				sku.setProductId(productWithBLOBs.getId());
				result+=skuService.add(sku);
			}
		}
		return result;
	}
	@Override
	public List<ProductWithBLOBs> query(ProductWithBLOBs productWithBLOBs, ProductExample productExample) {
		// TODO Auto-generated method stub
		if(productWithBLOBs.withPage==1)
			PageHelper.startPage(productWithBLOBs.getPageNo(), productWithBLOBs.getPageSize());
		return productMapper.selectByExampleWithBLOBs(productExample);
	}
	@Override
	public ProductWithBLOBs queryone(Integer id) {
		// TODO Auto-generated method stub
		return productMapper.selectByPrimaryKey(id);
	}

	@Override
	public int del(Integer id) {
		ProductWithBLOBs product = queryone(id);
		product.setIsDel(1);
		return productMapper.updateByPrimaryKeySelective(product);
	}

	@Override
	public int unDel(Integer id) {
		ProductWithBLOBs product = queryone(id);
		product.setIsDel(0);
		return productMapper.updateByPrimaryKeySelective(product);
	}

	@Override
	public int update(ProductWithBLOBs product) {
		return  productMapper.updateByPrimaryKeySelective(product);
	}

	@Override
	public List<ProductWithBLOBs> search(ProductQuery productQuery) {
		// TODO Auto-generated method stub
		if(productQuery.getWithPage()==1)
			PageHelper.startPage(productQuery.getPageNo(), productQuery.pageSize);
		return productMapper.search(productQuery);
	}
}
